import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/permission_helper.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

import '../global_easy_loading.dart';

class DioDownloadImg {
  static Future<bool> downAndSaveImg(
      String imgUrl, String name) async {
    if (await PermissionHelper.checkPhotosPermission(appContext.context!)) {
      var response = await Dio().get(imgUrl.replaceAll('"', ''),
          options: Options(responseType: ResponseType.bytes));
      // ImageGallerySaver.saveImage(imageBytes)
      var va = await ImageGallerySaver.saveImage(
          Uint8List.fromList(response.data),
          quality: 60,
          name: name);
      if (va != null) {
        customShowToast(S().save_success);
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  static Future<bool> bytesAndSaveImg(
      Uint8List bytes, String name, BuildContext context) async {
    if (await PermissionHelper.checkPhotosPermission(context)) {
      // var response = await Dio().get(imgUrl.replaceAll('"', ''),
      // options: Options(responseType: ResponseType.bytes));
      // file.readAsBytesSync();
      var va =
          await ImageGallerySaver.saveImage(bytes, quality: 60, name: name);
      if (va != null) {
        customShowToast(S().save_success);
        return true;
      } else {
        return false;
      }
    }
    return false;
  }

  static Future<bool> fileAndSaveImg(
      File file, String name, BuildContext context) async {
    if (await PermissionHelper.checkPhotosPermission(context)) {
      var va = await ImageGallerySaver.saveImage(file.readAsBytesSync(),
          quality: 60, name: name);
      if (va != null) {
        customShowToast(S.of(context).save_success);
        return true;
      } else {
        return false;
      }
    }
    return false;
  }
}
